package com.cloudbroker.bcs.platform.dav.middle.util;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class ActivityUtil {
    
    /**
     * 功能：将一个Map按照Key字母升序构成一个QueryString. 并且通过MD5加密后形成字符串
     * @param queryMap query内容
     * @param salt 加密salt
     * @return
     */
    public static String createHashedQueryString(Map<String, Object> queryMap, String salt) {
        Map<String, String> map = convertMap(queryMap);
        
        String qs = createQueryString(map, salt); //生成queryString方法可自己编写
        if (qs == null) {
            return null;
        }
        String md5String = md5QueryString(qs);
        return (qs.substring(0, qs.lastIndexOf("&")) + "&sign=" + md5String);
    }
    
    private static Map<String, String> convertMap(Map<String, Object> map) {
        Map<String, String> resultMap = new TreeMap<String, String>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() == null || entry.getValue().toString().isEmpty()) {
                continue;
            }
            resultMap.put(entry.getKey(), entry.getValue().toString());
        }
        return resultMap;
    }
    
    private static String createQueryString(Map<String, String> map, String salt) {
        StringBuilder sb = new StringBuilder();
        for (Entry<String, String> entry : map.entrySet()) {
            if (entry.getValue() == null || 0 == entry.getValue().length()) {
                 continue;
            }
            sb.append(entry.getKey());
            sb.append('=');
            sb.append(String.valueOf(entry.getValue()));
            sb.append('&');
        }
        sb.append("key");
        sb.append('=');
        sb.append(salt);
        String str = sb.toString();
        if (str == null || str.length() == 0) {
            return null;
        }
        return str;
    }
    
    private static String md5QueryString(String input) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        
        char[] charArray = input.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        
        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /**
     * 功能：根据输入的参数和约定好的校检码进行验证
     * @param queryMap query内容
     * @param salt 加密salt
     * @return
     */
    public static boolean validateHashedQueryString(Map<String, Object> queryMap, String salt) {
        Map<String, String> map = convertMap(queryMap);
        String validateHash = map.get("sign");
        map.remove("sign");
        String qs = createQueryString(map, salt); //生成queryString方法可自己编写
        String md5String = md5QueryString(qs);
        if (md5String != null && md5String.equals(validateHash)) {
            return true;
        }
        return false;
    }
    
    public static void main(String[] args) {
        
        //新建原始参数
        Map<String, Object> test = new HashMap<>();
//        test.put("mobile_tel", "15215905243");
//       /* test.put("amount", "10");*/
//        test.put("tenant_key", "asdfasdf");
//        test.put("page_no", 3);
//        test.put("page_count", 10);
//        //salt为双方约定好的key
       String salt = "d7015b6d7ee411e69907ecf4bbdef9f4";

        
        //创建表单提交数据form
        String formStr = createHashedQueryString(test, salt);
        System.out.println(formStr);
        //将form转换成map
        Map<String, Object> formMap = new HashMap<>();
        for (String s : formStr.split("&")) {
            formMap.put(s.split("=")[0], s.split("=")[1]);
        }
        //对提交数据form进行校验
        System.out.println(validateHashedQueryString(formMap, salt));
    }
    
}
